import subprocess,random,os,itertools,stat,time

random.seed(time.time())
def war(map,weights):
	"""
	Run a serie of battles to get improved generations of warriors !
	"""
	print "%i warriors will fight in this war ! " % len(weights)

	for i in range(10):
		winners = []
		for j in range(len(weights)):
			winners.append(battle(map,random.sample(weights,5)))
		return reproduce(winners)

def reproduce(weights):
	next = []
	for i in xrange(len(weights)/2  ):
		n1,n2 = cross(random.sample(weights,2))
		next.append(n1)
		next.append(n2)
	return next

def cross(weights):
	n1,n2 = [],[]

	for w1,w2 in zip(weights[0],weights[1]):
		if random.random() < 0.01:
			w1,w2 = random.uniform(-1,1),random.uniform(-1,1)
			
		r = random.random()
		if r  > 0.5:
			n1.append(w1)
			n2.append(w2)
		else:
			n1.append(w2)
			n2.append(w1)
	return n1,n2

def battle(map,weights):
	"""
	run a serie of fights on a map and return the winners
	"""
	winner = weights[0]
	for i,w in enumerate(weights[1:]):
		winner = fight(map,weights[i-1],weights[i])
	return winner

def fight(board,w1,w2):
	"""
	Takes to sets of weights, run a fight between the 2 matching nnbots and returns the weights of the winner
	"""
	import tempfile,struct
    	
	# write intermediate bash files
	nnbot = os.path.abspath("./nntron/nnBot.py")

	tmpfile1 = tempfile.NamedTemporaryFile('w',dir='/dev/shm',delete=False)
	for w in w1:
		tmpfile1.write(struct.pack('f',w))
	tmpfile1.close()
	
	bash1 = open("../data/tmp/fighter1.sh",'w')
	bash1.write("#!/bin/bash\n%s %s"% (nnbot,tmpfile1.name))
	bash1.close()
	
	
	os.chmod("../data/tmp/fighter1.sh",stat.S_IRWXU)

	tmpfile2 = tempfile.NamedTemporaryFile('w',dir='/dev/shm',delete=False)
	tmpfile2.write(struct.pack('f'*len(w2),*w2))
	tmpfile2.close()

	bash2 = open("../data/tmp/fighter2.sh", 'w')
	bash2.write("#!/bin/bash\n%s %s" % (nnbot,tmpfile2.name))
	bash2.close()
	os.chmod("../data/tmp/fighter2.sh",stat.S_IRWXU)
	# FIGHT !!
	
   	map = '../data/maps/' + random.choice(filter(lambda x:x[-3:]=="txt",os.listdir('../data/maps')))
	output = subprocess.Popen(["java", "-jar", "../ressources/engine/Tron.jar", map, bash1.name, bash2.name, '0'], stdout=subprocess.PIPE).communicate()[0]
	
	os.remove(tmpfile2.name)
	os.remove(tmpfile1.name)

	print output
    
 	if ('One') in output[-20:]:
 		print  'w1 wins!'
 		return w1

 	elif 'Two' in output[-20:]:
 		print 'w2 wins!'
 		return w2
 	 
 	elif 'Draw' in output[-20:]:
 		print 'draw'
 		return fight(board,w1,w2)
 
        


